package com.sgb.kjwl.view.ui.activity.self.publish;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import androidx.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.widget.Toast;

import com.bigkoo.pickerview.builder.OptionsPickerBuilder;
import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnOptionsSelectListener;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.OptionsPickerView;
import com.bigkoo.pickerview.view.TimePickerView;
import com.sgb.kjwl.AppActivity;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.ActivityPersonnelPublishBinding;
import com.sgb.kjwl.di.self.DaggerSelfComponent;
import com.sgb.kjwl.di.self.SelfModule;
import com.sgb.kjwl.model.entity.user.AddTalentEntity;
import com.sgb.kjwl.model.entity.user.AddressEntity;
import com.sgb.kjwl.model.entity.user.TalentTypeEntity;
import com.swgk.core.event.EventConstant;
import com.sgb.kjwl.view.event.self.PersonnelPublishEvent;
import com.sgb.kjwl.view.widget.SkillPopWindow;
import com.sgb.kjwl.viewmodel.self.publish.PersonnelPublishModel;
import com.swgk.core.base.di.AppComponent;
import com.swgk.core.customview.ItemInputTextView;
import com.swgk.core.dialog.BasePopWindow;
import com.swgk.core.util.CheckUtils;
import com.swgk.core.util.DateUtils;
import com.swgk.core.util.MDateUtil;
import com.swgk.core.util.MLog;

import org.greenrobot.eventbus.EventBus;
import org.jsoup.internal.StringUtil;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import javax.inject.Inject;

public class PersonnelPublishActivity extends AppActivity implements ItemInputTextView.OnWholeItemClickListener {
    private ActivityPersonnelPublishBinding binding;
    private Thread thread;
    private static final int MSG_LOAD_DATA = 0x0001;
    private static final int MSG_LOAD_SUCCESS = 0x0002;
    private static final int MSG_LOAD_FAILED = 0x0003;
    private static final int MSG_LOAD_DATA_TYPE = 0x0004;
    private static final int MSG_LOAD_SUCCESS_TYPE = 0x0005;
    private final int MAX_LENGTH = 500;
    private boolean isLoaded = false;
    private boolean isTypeLoaded = false;
    private SkillPopWindow skillPopWindow;
    private List<AddressEntity<List<AddressEntity>>> addressEntityList;
    private List<TalentTypeEntity<List<TalentTypeEntity>>> talentTypeEntities;
    private List<TalentTypeEntity> talentTypeChildList;
    private List<List<AddressEntity>> opt2;
    private List<String> skillList;
    private String categoryNo;
    private int cityPosition1;
    private int cityPosition2;
    private int industryPosition;
    private int skillPosition;
    private AddTalentEntity addTalentEntity;
    private Date today;
    private Calendar selectedDate;
    @Inject
    PersonnelPublishModel viewModel;

    public static void start(Context context) {
        start(context, null);
    }

    public static void start(Context context, Intent extras) {
        Intent intent = new Intent();
        intent.setClass(context, PersonnelPublishActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        if (extras != null) {
            intent.putExtras(extras);
        }
        context.startActivity(intent);
    }

    @Override
    protected void setupActivityComponent(AppComponent appComponent) {
        DaggerSelfComponent.builder()
                .appComponent(appComponent)
                .selfModule(new SelfModule(this))
                .build()
                .inject(this);
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initView() {
        binding = DataBindingUtil.setContentView(PersonnelPublishActivity.this, R.layout.activity_personnel_publish);
        binding.setViewModel(viewModel);
        binding.backView.setOnClickListener(this);
        binding.nextView.setOnClickListener(this);
        binding.itemTvPlace.setOnWholeItemClickListener(this);
        binding.itemTvBirthday.setOnWholeItemClickListener(this);
        binding.itemTvIndustry.setOnWholeItemClickListener(this);
        binding.itemTvSkill.setOnWholeItemClickListener(this);
        binding.itemTvWorkYear.setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL);
        binding.itemTvPhone.setInputType(InputType.TYPE_CLASS_NUMBER);
        binding.itemTvName.getContent_edt().addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                binding.itemTvTitle.setContent(binding.itemTvSkill.getContent() + binding.itemTvName.getContent());
            }
        });
    }

    @Override
    protected void init() {
//        viewModel.getPersonnerDetailModel();
        viewModel.getPersonModel();
        opt2 = new ArrayList<>();
        skillList = new ArrayList<>();
        selectedDate = Calendar.getInstance();
        skillPopWindow = new SkillPopWindow(PersonnelPublishActivity.this);
        skillPopWindow.setBgView(binding.grayLayout);
        skillPopWindow.setOnResultClick(new BasePopWindow.OnResultClick() {
            @Override
            public void result(Object key1, Object key2, Object key3) {
                List<TalentTypeEntity> talentTypeChildList = (List<TalentTypeEntity>) key1;
                if (talentTypeChildList.size() > 0) {
                    skillList.clear();
                }
                String content = "";
                for (int i = 0; i < talentTypeChildList.size(); i++) {
                    skillList.add(talentTypeChildList.get(i).getNo());
                    if (i == talentTypeChildList.size() - 1) {
                        content = content + talentTypeChildList.get(i).getName();
                    } else {
                        content = content + talentTypeChildList.get(i).getName() + ",";
                    }
                }
                binding.itemTvSkill.setContent(content);
                //专业技能编号列表
                viewModel.addTalentEntity.get().setSkillList(skillList);

                binding.itemTvTitle.setContent(binding.itemTvSkill.getContent() + binding.itemTvName.getContent());
            }
        });
    }

    public void showTypeView(List<TalentTypeEntity<List<TalentTypeEntity>>> data) {
        this.talentTypeEntities = data;
        if (viewModel.addTalentEntity.get().getId() == null) {
            showIndustryPop();
        }
        viewModel.getDefaultSkillModel(viewModel.addTalentEntity.get().getCategoryNo(), data);
    }

    public void showDetailView(AddTalentEntity data) {
        if (data.getId() == null) {
            return;
        }
        addTalentEntity = data;
        if (data.getAreaName() != null) {
            binding.itemTvPlace.setContent(data.getProvinceName() + data.getAreaName());
        }
        if (data.getAgeTime() != 0) {
            selectedDate.setTime(new Date(data.getAgeTime()));
            binding.itemTvBirthday.setContent(MDateUtil.getByTimestamp(Long.parseLong(data.getAgeTime() + ""), MDateUtil.Format.FORMART5.name));
        }
        try {
            binding.itemTvSkill.setContent(StringUtil.join(data.getSkillName(), ","));
        } catch (Exception e) {
            e.printStackTrace();
        }
        viewModel.addTalentEntity.set(data);
        viewModel.getTypeModel();
//        skillPopWindow.setAlreadyData(data.getSkillList());
    }

    public void showDefaultSkill(List<TalentTypeEntity> talentTypeChildList) {
        this.talentTypeChildList = talentTypeChildList;
        skillPopWindow.setData(talentTypeChildList, true, addTalentEntity.getSkillList());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.back_view:
                finish();
                break;
            case R.id.next_view:
                if (TextUtils.isEmpty(binding.itemTvName.getContent())) {
                    Toast.makeText(this, "请填写姓名", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPlace.getContent())) {
                    Toast.makeText(this, "请选择所在地", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvIndustry.getContent())) {
                    Toast.makeText(this, "请选择所属行业", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvSkill.getContent())) {
                    Toast.makeText(this, "请选择专业技能", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvBirthday.getContent())) {
                    Toast.makeText(this, "请选择出生年份", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!TextUtils.isEmpty(binding.itemTvWorkYear.getContent()) && (Integer.valueOf(binding.itemTvWorkYear.getContent()) <= 0)) {
                    Toast.makeText(this, "工龄为大于0的整数", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvTitle.getContent())) {
                    Toast.makeText(this, "请填写标题", Toast.LENGTH_SHORT).show();
                    return;
                } else if (TextUtils.isEmpty(binding.itemTvPhone.getContent())) {
                    Toast.makeText(this, "请选填写联系电话", Toast.LENGTH_SHORT).show();
                    return;
                } else if (!CheckUtils.isMobileNum(binding.itemTvPhone.getContent())) {
                    Toast.makeText(this, "请填写正确的联系电话", Toast.LENGTH_SHORT).show();
                    return;
                }
                EventBus.getDefault().postSticky(PersonnelPublishEvent.make().setMessageTag(EventConstant.EVENT_PUBLISH_PERSON_NEXT).setMessageData(viewModel.addTalentEntity.get()));
                PersonPublishNextActivity.start(this);
                break;
        }
    }

    @Override
    public void OnWholeItemClick(View view) {
        switch (view.getId()) {
            case R.id.item_tv_place:
                if (addressEntityList != null) {
                    showAddressPop();
                } else {
                    viewModel.getAddressModel();
                }
                break;
            case R.id.item_tv_birthday:
                showTimePop();
                break;
            case R.id.item_tv_industry:
                MLog.d("test", "id-----------------4 " + talentTypeEntities + "    " + isTypeLoaded);
                if (talentTypeEntities != null) {
                    if (isTypeLoaded) {
                        showIndustryPop();
                    } else {
                        mHandler.sendEmptyMessage(MSG_LOAD_DATA_TYPE);
                    }
                } else {
                    viewModel.getTypeModel();
                }

                break;
            case R.id.item_tv_skill:
                if (TextUtils.isEmpty(binding.itemTvIndustry.getContent())) {
                    Toast.makeText(this, "请先选择所属行业", Toast.LENGTH_SHORT).show();
                } else {
                    skillPopWindow.showDownPopwindow(binding.grayLayout, true);
                }
                break;
        }
    }

    //时间选择器
    public void showTimePop() {
        TimePickerView timePicker = new TimePickerBuilder(PersonnelPublishActivity.this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                if (today == null)
                    today = new Date();
                int compareTo = today.compareTo(date);
                if (compareTo == -1) {
                    Toast.makeText(PersonnelPublishActivity.this, "请选择小于今天的日期", Toast.LENGTH_SHORT).show();
                } else {
                    try {
                        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                        String format = sdf.format(date);
                        selectedDate.setTime(date);
                        binding.itemTvBirthday.setContent(format);
                        //出生年份
                        viewModel.addTalentEntity.get().setAgeTime(DateUtils.dateTo13Timestamp(binding.itemTvBirthday.getContent()));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        }).build();
        timePicker.show();
        timePicker.setDate(selectedDate);
    }

    public void showAddressView(List<AddressEntity<List<AddressEntity>>> data) {
        this.addressEntityList = data;
        if (isLoaded) {
            showAddressPop();
        } else {
            mHandler.sendEmptyMessage(MSG_LOAD_DATA);
        }
    }

    private void showIndustryPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(PersonnelPublishActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = talentTypeEntities.get(options1).getName();
                binding.itemTvIndustry.setContent(content);
                industryPosition = options1;
                talentTypeChildList = talentTypeEntities.get(industryPosition).getChildren();
                skillPopWindow.setData(talentTypeChildList, true, null);
                categoryNo = talentTypeEntities.get(industryPosition).getNo();
                //所属行业编号
                viewModel.addTalentEntity.get().setCategoryNo(categoryNo);
                binding.itemTvSkill.setContent("");
                viewModel.addTalentEntity.get().setSkillList(null);
            }
        }).build();
        businessOption.setPicker(talentTypeEntities);
        businessOption.setSelectOptions(industryPosition);
        businessOption.show();
    }


    private void showAddressPop() {
        OptionsPickerView businessOption = new OptionsPickerBuilder(PersonnelPublishActivity.this, new OnOptionsSelectListener() {
            @Override
            public void onOptionsSelect(int options1, int options2, int options3, View v) {
                String content = addressEntityList.get(options1).getName()
                        + opt2.get(options1).get(options2).getName();
                binding.itemTvPlace.setContent(content);
                cityPosition1 = options1;
                cityPosition2 = options2;
                //地址编号列表
                try {
                    viewModel.addTalentEntity.get().setAreaNo(opt2.get(options1).get(options2).getNo());
                } catch (Exception e) {

                }
            }
        }).build();
        businessOption.setPicker(addressEntityList, opt2);
        businessOption.setSelectOptions(cityPosition1, cityPosition2);
        businessOption.show();
    }

    @SuppressLint("HandlerLeak")
    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_LOAD_DATA:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_DATA_TYPE:
                    if (thread == null) {//如果已创建就不再重新创建子线程了
                        thread = new Thread(() -> {
                            // 子线程中解析省市区数据
                            initTypeJsonData();
                        });
                        thread.start();
                    }
                    break;
                case MSG_LOAD_SUCCESS:
                    showAddressPop();
                    isLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_SUCCESS_TYPE:
                    showIndustryPop();
                    isTypeLoaded = true;
                    thread = null;
                    break;
                case MSG_LOAD_FAILED:
                    break;
            }
        }
    };

    private void initJsonData() {
        for (int i = 0; i < addressEntityList.size(); i++) {
            if (addTalentEntity != null && viewModel.addTalentEntity.get().getProvinceNo().equals(addressEntityList.get(i).getNo())) {
                cityPosition1 = i;
            }
            opt2.add(addressEntityList.get(i).getChildren());
        }
        if (addTalentEntity != null) {
            for (int i = 0; i < opt2.size(); i++) {
                if (viewModel.addTalentEntity.get().getAreaNo().equals(addressEntityList.get(cityPosition1).getChildren().get(i).getNo())) {
                    cityPosition2 = i;
                    break;
                }
                opt2.add(addressEntityList.get(i).getChildren());
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS);
    }

    private void initTypeJsonData() {
        for (int i = 0; i < talentTypeEntities.size(); i++) {
            if (addTalentEntity != null && viewModel.addTalentEntity.get().getCategoryNo().equals(talentTypeEntities.get(i).getNo())) {
                industryPosition = i;
                break;
            }
        }
        mHandler.sendEmptyMessage(MSG_LOAD_SUCCESS_TYPE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mHandler != null) {
            mHandler.removeCallbacksAndMessages(null);
        }
    }
}

